package com.yinhe.overtimecalc;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;

import com.yinhe.overtimecalc.server.ServerClient;
import com.yinhe.overtimecalc.server.TCPClient;
import com.yinhe.overtimecalc.server.UdpClient;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private TextView sumTextView = null;
    private ListView overTimesListView = null;
    private OverTime sumOverTime = null;
    private List<OverTime> overTimes = null;
    private ArrayAdapter<OverTime> arrayAdapter = null;
    private TimePicker timePicker = null;
    private ServerClient serverClient;
    private ThreadPoolExecutor threadPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initMainView();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serverClient!=null){
            serverClient.close();
        }
    }

    private void init(){
//        serverClient = new UdpClient();
        serverClient = new TCPClient();
        threadPool = new ThreadPoolExecutor(10,
                30,
                30,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<Runnable>(10),
                new CustomThreadFactory(),
                new CustomRejectedExecutionHandler());
    }

    private void initMainView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.fab_add:
                        // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        sumOverTime();
                        break;
                    case R.id.fab_delete:
                        subtractOverTime();
                        break;
                    case R.id.fab_clear:
                        clearView();
                        break;
                    default:
                }
            }
        };

        FloatingActionButton fab_add = (FloatingActionButton) findViewById(R.id.fab_add);
        FloatingActionButton fab_delete = (FloatingActionButton) findViewById(R.id.fab_delete);
        FloatingActionButton fab_clear = (FloatingActionButton) findViewById(R.id.fab_clear);
        fab_add.setOnClickListener(onClickListener);
        fab_delete.setOnClickListener(onClickListener);
        fab_clear.setOnClickListener(onClickListener);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        sumTextView = (TextView) findViewById(R.id.sumTextView);
        overTimesListView = (ListView) findViewById(R.id.overTimesListView);
        timePicker = (TimePicker) findViewById(R.id.overTimePicker);
        timePicker.setIs24HourView(true);
        resetTimePicker(0, 0);
        sumOverTime = new OverTime(0, 0);
        overTimes = new ArrayList<>();
        arrayAdapter = new ArrayAdapter<OverTime>(
                MainActivity.this,
                android.R.layout.simple_list_item_1,
                overTimes
        );
        overTimesListView.setAdapter(arrayAdapter);
    }

    public void sumOverTime() {
        OverTime overTime = getNewOverTime();
        sumOverTime.add(overTime);
        updateView(overTime);
//        resetTimePicker(0, 0);
    }

    private void subtractOverTime() {
        OverTime overTime = getNewOverTime();
        sumOverTime.subtract(overTime);
        overTime.setType(TYPE.NEGATIVE);
        updateView(overTime);
    }

    private OverTime getNewOverTime() {
        int hour = timePicker.getCurrentHour();
        int miunte = timePicker.getCurrentMinute();
        OverTime overTime = new OverTime(hour, miunte);
        return overTime;
    }

    private void updateView(OverTime overTime) {
        overTimes.add(overTime);
        arrayAdapter.notifyDataSetChanged();
        sumTextView.setText(sumOverTime.toString());
        overTimesListView.smoothScrollToPosition(arrayAdapter.getCount() - 1);
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                serverClient.sendMessage(sumOverTime.toString());
                serverClient.getMessage();
            }
        });

    }



    private void clearView() {
        resetTimePicker(0, 0);
        sumOverTime.setMinute(0);
        sumOverTime.setHour(0);
        sumTextView.setText(sumOverTime.toString());
        overTimes.clear();
        arrayAdapter.notifyDataSetChanged();
    }

    private void resetTimePicker(int hour, int minute) {
        timePicker.setCurrentHour(hour);
        timePicker.setCurrentMinute(minute);
    }

    private class CustomThreadFactory implements ThreadFactory {

        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String threadName = MainActivity.class.getSimpleName() + count.addAndGet(1);
            System.out.println(threadName);
            t.setName(threadName);
            return t;
        }
    }


    private class CustomRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // 记录异常
            // 报警处理等
            System.out.println("error.............");
        }
    }
}
